package com.chen.controller;

import com.chen.annotation.OptLog;
import com.chen.common.Constants;
import com.chen.common.OptTypeConst;
import com.chen.common.Result;
import com.chen.entity.Dict;
import com.chen.service.impl.DictServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author chenchao
 * @date 2022/6/17 14:11
 */
@RestController
@Api(value = "DictController",tags = "数据字典")
@RequestMapping("/dict")
public class DictController {

    @Autowired
    private DictServiceImpl dictService;

    @Resource
    private RedisTemplate redisTemplate;


    @PostMapping("/save")
    @ApiOperation(value = "新增字典或者更新")
    @OptLog(optType = OptTypeConst.SAVE_OR_UPDATE)
    public Result addDict(@RequestBody Dict dict){
        flushRedis();
        dictService.saveOrUpdate(dict);
        setCache();
        return Result.success();
    }


//根据id进行删除
    @DeleteMapping("/deleteDict/{id}")
    @ApiOperation(value = "删除字典")
    @OptLog(optType = OptTypeConst.REMOVE)
    public Result deleteDict(@PathVariable("id") int id){
        dictService.deleteDict(id);
        setCache();
        return Result.success();
    }

//批量删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "批量删除")
    @OptLog(optType = OptTypeConst.REMOVE_BATH)
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        dictService.removeByIds(ids);
//        演示设置5s种过期
//        redisTemplate.opsForValue().set("sss","sssss",5, TimeUnit.SECONDS);
        return Result.success();
    }


    @RequestMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result selectDict(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "") String name){

        return Result.success(dictService.selectPage(pageNum, pageSize, name));
    }


    // 删除缓存
    private void flushRedis() {
       redisTemplate.delete(Constants.DICT_TYPE_ICON);
    }

    // 设置缓存
    private void setCache() {
        redisTemplate.opsForValue().set(Constants.DICT_TYPE_ICON, dictService.list());
    }

}
